package zuel.innovation.disley.train.controller;

import cn.fabrice.common.constant.BaseConstants;
import cn.fabrice.common.pojo.BaseResult;
import cn.fabrice.common.pojo.DataResult;
import cn.fabrice.jfinal.annotation.Param;
import cn.fabrice.jfinal.annotation.ValidateParam;
import cn.fabrice.jfinal.ext.cros.interceptor.CrossInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import zuel.innovation.disley.common.module.*;
import zuel.innovation.disley.homework.service.HomeworkService;
import zuel.innovation.disley.train.service.TrainService;
import zuel.innovation.disley.train.service.TrainStudentService;
import zuel.innovation.disley.user.service.UserService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


// 路由扫描
@Before(CrossInterceptor.class)
@Path("/train")
@ValidateParam


public class TrainController extends Controller {
    @Inject
    UserService service;
    @Inject
    TrainService trainService;
    @Inject
    HomeworkService homeworkService;
    @Inject
    TrainStudentService trainStudentService;


    /**
     * 分页显示全部培训信息
     *
     * @param page     页数
     * @param pageSize 每页的信息数目
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void selectTrainsByPages(int page, int pageSize) {
        Page<Record> trains = Db.paginate(page, pageSize, "select tr_id,tr_title,tr_start,tr_type,tr_sum,tr_num,tr_work,tr_state", "from train where tr_deleted=0");
        if (trains.getList().isEmpty()) {
            renderJson(BaseResult.fail("暂无培训信息"));
        } else {
            renderJson(DataResult.data(trains));
        }
    }


    /**
     * 查看某一次培训的详细信息
     *
     * @param trId 培训编号
     */
    @Param(name = "trId", required = true)
    public void selectOneTrainById(int trId) {
        Kv cond = Kv.by("trId", trId);
        List<Train> trainList = trainService.list(cond, "selectOneTrainById");
        if (trainList.isEmpty()) {
            renderJson(BaseResult.fail("请输入正确的培训id"));
        } else {
            renderJson(DataResult.data(trainList));
        }
    }


    /**
     * 分页展示某一次培训的全部参与用户
     *
     * @param page     页数
     * @param pageSize 每页的信息数目
     * @param trId     培训编号
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    @Param(name = "trId", required = true)
    public void selectTrainUserByPages(int page, int pageSize, int trId) {
        Page<Record> trainUser = Db.paginate(page, pageSize, "select train_student.u_id,`user`.u_name,homework_user.hu_update,homework_user.hu_comment",
                "from user,homework,homework_user,train_student\n" +
                        "where train_student.tr_id=homework.tr_id and homework.h_id=homework_user.h_id and `user`.u_id=train_student.u_id  \n" +
                        "and `user`.u_id=homework_user.u_id and train_student.tr_id=" + trId);
        renderJson(DataResult.data(trainUser));
    }


    /**
     * 模糊搜索并分页展示
     *
     * @param content  内容
     * @param page     页数
     * @param pageSize 每页的信息数目
     * @param trId     培训编号
     */
    @Param(name = "content", required = true)
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void selectTrainUser(String content, int page, int pageSize, int trId) {
        Kv cond = Kv.by("content", content);
        cond.set("trId", trId);
        Page<Record> trainUser = Db.paginate(page, pageSize, "select train_student.u_id,`user`.u_name,homework_user.hu_update,homework_user.hu_comment",
                "from user,homework,homework_user,train_student\n" +
                        "where train_student.tr_id=homework.tr_id and homework.h_id=homework_user.h_id and `user`.u_id=train_student.u_id  \n" +
                        "and `user`.u_id=homework_user.u_id and train_student.tr_id=" + trId + " and `user`.u_name like '%" + content + "%'");

        renderJson(DataResult.data(trainUser));
    }


    /**
     * 管理员发布培训信息
     *
     * @param trStart    培训开始时间
     * @param trEnd      培训结束时间
     * @param trTitle    培训标题
     * @param trType     培训类型 0-默认 1-前端 2-后端
     * @param trLocation 培训地点
     * @param trText     培训内容
     * @throws ParseException
     */
    @Param(name = "trStart", required = true)
    @Param(name = "trEnd", required = true)
    @Param(name = "trTitle", required = true)
    @Param(name = "trType", required = true)
    @Param(name = "trLocation", required = true)
    @Param(name = "trText", required = true)
    public void addTrain(Date trStart, Date trEnd, String trTitle, int trType, String trLocation, String trText) throws ParseException {
        int id=getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId",id);
        User user = service.get(cond,"getByUId");
        Train train=new Train();
        train.setTrState(0);
        train.setTrStart(trStart);
        train.setTrEnd(trEnd);
        train.setTrLocation(trLocation);
        train.setTrText(trText);
        train.setTrSum(14);
        train.setTrNum(0);
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date trCreate=df.parse(df.format(System.currentTimeMillis()));
        train.setTrCreate(trCreate);
        train.setTrDeleted(0);
        train.setTrWork(0);
        train.setTrType(trType);
        train.setTrTitle(trTitle);
        HashMap<String,Object> data = new HashMap<>();
        data.put("uid",id);
        data.put("name",user.getUName());
        data.put("ok",train.save()?BaseResult.ok():BaseResult.fail());
        renderJson(DataResult.data(data));
    }


    /**
     * 用户报名参加培训
     *
     * @param trId 培训编号
     * @throws ParseException
     */
    @Param(name = "trId", required = true)
    public void addTrainUser(int trId) throws ParseException {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        TrainStudent trainStudent = new TrainStudent();
        trainStudent.setUId(id);
        trainStudent.setTrId(trId);
        trainStudent.setTsIsappear(0);
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date tsCreate = df.parse(df.format(System.currentTimeMillis()));
        trainStudent.setTsCreate(tsCreate);
        trainStudent.setTsIsdeleted(0);
        renderJson(trainStudent.save() ? BaseResult.ok() : BaseResult.fail());

    }


    /**
     * 签到
     *
     * @param trId 培训编号
     * @throws ParseException
     */
    @Param(name = "trId", required = true)
    public void signIn(int trId) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date tsTime = df.parse(df.format(System.currentTimeMillis()));
        int uId = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", uId);
        cond.set("trId", trId);
        TrainStudent trainStudent = trainStudentService.get(cond, "selectTrainStudent");
        trainStudent.setTsTime(tsTime);
        Train train = trainService.get(cond, "selectTrain");
        int num = train.getTrNum();
        train.setTrNum(num + 1);
        renderJson(trainStudent.update() && train.update() ? BaseResult.ok() : BaseResult.fail());
    }


    /**
     * 管理员发布签到
     */
    @Param(name = "trId",required = true)
    public void releaseTrain(int trId) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date currentTime=df.parse(df.format(System.currentTimeMillis()));
        Kv cond=Kv.by("trId",trId);
        Train train=trainService.get(cond,"selectOneTrainById");
        Date start=train.getTrStart();
        Date end=train.getTrEnd();
        if(currentTime.before(start)){
            renderJson(BaseResult.fail("签到暂未开始"));
        }
        else if(currentTime.after(end)){
            train.setTrState(1);
            renderJson(BaseResult.fail("签到已结束"));
        }else {
            renderJson(BaseResult.fail("正在签到"));
        }
    }


    /**
     * 判断此用户是否参加某次培训
     */
    @Param(name = "trId",required = true)
    public void isAttendTrain(int trId){
        int uId=getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond=Kv.by("trId",trId);
        cond.set("uId",uId);
        TrainStudent trainStudent=trainStudentService.get(cond,"selectTrainStudent");
        if (trainStudent==null){
            renderJson(BaseResult.fail("该用户未参加此次培训"));
        }else {
            renderJson(DataResult.data(trainStudent));
        }

    }

}
